package com.baidu.infinity.ui.fragment.home.shape

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.graphics.createBitmap
import com.baidu.infinity.ui.util.state.ShapeState
import kotlin.collections.ArrayList

class Layer(val id: Int,val width: Int,val height: Int) {
    val shapeList: ArrayList<BaseShape> = arrayListOf()
    private var mCanvas: Canvas
    private var mBitmap: Bitmap = createBitmap(width, height)
    private var currentShape: BaseShape ?= null
    private var currentSelectedShape: BaseShape ?= null
    init {
        mCanvas = Canvas(mBitmap)
    }
    fun getBitmap(): Bitmap{
        return mBitmap
    }
    fun addShape(shape: BaseShape,startX: Float,startY: Float){
        currentShape = shape
        shapeList.add(shape)
        currentShape!!.setStartPoint(startX,startY)
    }
    fun setEndPoint(endX: Float, endY: Float){
        if(shapeList.isNotEmpty()){
            if(currentSelectedShape == null){
                currentShape!!.setEndPoint(endX, endY)
            }else{
                currentSelectedShape!!.setEndPoint(endX, endY)
            }
        }

    }
    fun draw(){
        mBitmap.eraseColor(Color.TRANSPARENT)
        shapeList.forEach{shape ->
            shape.draw(mCanvas)
        }
    }
    @RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
    fun undo(){
        if (shapeList.isNotEmpty()){
            shapeList.removeLast()
        }
    }
    fun clear(){
        shapeList.clear()
    }
    @RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
    fun getCurrentShape(): BaseShape?{
        if(shapeList.size == 0)return null
        else return shapeList.last
    }
    fun updateSelectedShape(x: Float,y: Float) {
        var isOnlyOne = false
        shapeList.reversed().forEach {shape ->
            if(shape.containsPointInRect(x,y) && !isOnlyOne){
                if(shape.mState == ShapeState.SELECT){
                    shape.updateSelectState(x,y)
                    currentSelectedShape = shape
                }
                shape.mState = ShapeState.SELECT
                isOnlyOne = true
            }else{
                if(!isOnlyOne){
                    currentSelectedShape = null
                }
                shape.mState = ShapeState.NORMAL
            }
        }
    }
    fun calculateSelectLocation(x: Float,y: Float){
        currentSelectedShape?.calculateLotation(x,y)
    }
    fun updateSelectedShapeColor(x: Float,y: Float) {
        shapeList.reversed().forEach {shape ->
            if(shape.containsPoint(x,y)){
                shape.fillColor()
                return
            }
        }
    }
}